<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Socket.IO Client</title>
    <script src="js/socket.io.min.js"></script>
</head>
<body>

<h1>Socket.IO Client</h1>
<button onclick="sendMessage()">Send Message</button>
<div id="messages"></div>

<script>
    // 连接到服务器
    const socket = io('http://localhost:9001/websocket', {
        transports: ['websocket']  // 强制客户端使用 WebSocket 协议
    });  // 服务器地址

    // 监听连接事件
    socket.on('connect', () => {
        console.log('Connected to Socket.IO server');
        const messagesDiv = document.getElementById('messages');
        messagesDiv.innerHTML += `<p>Connected to server!</p>`;
    });

    // 监听服务器发来的消息
    socket.on('message', (msg) => {
        console.log('Received message from server:', msg);
        const messagesDiv = document.getElementById('messages');
        messagesDiv.innerHTML += `<p>Received from server: ${msg}</p>`;
    });

    // 发送消息到服务器
    function sendMessage() {
        const msg = 'Hello from client!';
        console.log('Sending message to server:', msg);
        socket.emit('message', msg);
    }

    // 监听连接关闭
    socket.on('disconnect', () => {
        console.log('Disconnected from Socket.IO server');
    });
</script>

</body>
</html>
